package com.net.udpTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpServer {

    private static final int UDP_MSS = 64 * 1024;
    public static void main(String[] args) throws IOException {

        DatagramSocket udpSocket = new DatagramSocket(7877);

        while (true) {

            byte[] receiveData = new byte[UDP_MSS];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            udpSocket.receive(receivePacket);
            String receivedMessage = new String(receivePacket.getData()).trim();
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();

            System.out.println("Server Received message: " + receivedMessage + " from " + clientAddress + ":" + clientPort);

            // 模拟处理请求并发送响应
            String responseMessage = "Echo: " + receivedMessage;
            byte[] sendData = responseMessage.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
            udpSocket.send(sendPacket);
        }
    }
}
